<template>
  <div class="profile-header">
    <div class="profile-info">
      <div 
        class="avatar-container" 
        v-if="isCurrentUser" 
        @click="handleAvatarClick"
      >
        <img :src="user?.avatar || '/default-avatar.png'" :alt="user?.username" class="avatar">
        <div class="avatar-overlay">
          <i class="fas fa-camera"></i>
        </div>
      </div>
      <img v-else :src="user?.avatar || '/default-avatar.png'" :alt="user?.username" class="avatar">
      <div class="user-meta">
        <h1 class="username">{{ user?.username }}</h1>
        <p class="bio">{{ user?.bio || '这个人很懒，还没有写简介' }}</p>
        <div class="stats">
          <div class="stat-item">
            <span class="value">{{ user?.stats?.articles || 0 }}</span>
            <span class="label">文章</span>
          </div>
          <div class="stat-item">
            <span class="value">{{ user?.stats?.followers || 0 }}</span>
            <span class="label">粉丝</span>
          </div>
          <div class="stat-item">
            <span class="value">{{ user?.stats?.following || 0 }}</span>
            <span class="label">关注</span>
          </div>
        </div>
        <button 
          v-if="!isCurrentUser" 
          class="follow-btn" 
          :class="{ following: isFollowing }" 
          @click="handleFollowClick"
        >
          {{ isFollowing ? '已关注' : '关注' }}
        </button>
      </div>
    </div>
   
    <!-- 头像裁剪弹窗 -->
    <div class="cropper-modal" v-if="showCropper">
      <div class="cropper-container">
        <div class="cropper-header">
          <h3>更新头像</h3>
          <button class="close-btn" @click="showCropper = false">
            <i class="fas fa-times"></i>
          </button>
        </div>
        <div class="cropper-content">
          <Cropper
            v-if="imageUrl"
            ref="cropper"
            :src="imageUrl"
            :stencilProps="{
              aspectRatio: 1
            }"
          />
          <div v-else class="upload-placeholder">
            <input
              type="file"
              accept="image/*"
              @change="handleFileChange"
              ref="fileInput"
              style="display: none"
            >
            <button class="select-btn" @click="$refs.fileInput.click()">
              <i class="fas fa-plus"></i>
              选择图片
            </button>
          </div>
        </div>
        <div class="cropper-footer">
          <button class="cancel-btn" @click="showCropper = false">取消</button>
          <button 
            v-if="imageUrl" 
            class="confirm-btn" 
            @click="handleCropUpload"
            :disabled="uploading"
          >
            {{ uploading ? '上传中...' : '确认' }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { Cropper } from 'vue-advanced-cropper'
import 'vue-advanced-cropper/dist/style.css'
import { useUserStore } from '../stores/userStore'
import { useProfileStore } from '../stores/profileStore'

const props = defineProps({
  user: Object,
  isCurrentUser: Boolean,
  isFollowing: Boolean
})

console.log('Current props:', {
  user: props.user,
  isCurrentUser: props.isCurrentUser,
  isFollowing: props.isFollowing
})

const emit = defineEmits(['toggle-follow'])
const userStore = useUserStore()
const profileStore = useProfileStore()

const showCropper = ref(false)
const imageUrl = ref('')
const uploading = ref(false)
const cropper = ref(null)

// 处理头像点击
const handleAvatarClick = () => {
  console.log('Avatar clicked, isCurrentUser:', props.isCurrentUser)
  showCropper.value = true
}

// 处理文件选择
const handleFileChange = (e) => {
  const file = e.target.files[0]
  if (file) {
    const reader = new FileReader()
    reader.onload = (e) => {
      imageUrl.value = e.target.result
    }
    reader.readAsDataURL(file)
  }
}

// 处理裁剪和上传
const handleCropUpload = async () => {
  if (!cropper.value) return
  
  try {
    uploading.value = true
    
    // 获取裁剪后的图片数据
    const { canvas } = cropper.value.getResult()
    const dataUrl = canvas.toDataURL('image/png')
    const blob = await (await fetch(dataUrl)).blob()
    
    // 创建文件对象
    const file = new File([blob], 'avatar.png', { type: 'image/png' })
    
    // 上传头像
    await userStore.updateAvatar(props.user.id, file)
    
    // 刷新用户资料
    await profileStore.fetchUserProfile(props.user.id)
    
    // 关闭弹窗并重置状态
    showCropper.value = false
    imageUrl.value = ''
    
    // 显示成功提示
    alert('头像更新成功！')
    
  } catch (error) {
    console.error('上传头像失败:', error)
    alert('上传头像失败，请重试')
  } finally {
    uploading.value = false
  }
}

const handleFollowClick = () => {
  if (userStore.currentUser?.id === props.user?.id) {
    alert('不能关注自己哦！')
    return
  }
  emit('toggle-follow')
}
</script>

<style scoped>
.profile-header {
  background: white;
  border-radius: 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  overflow: hidden;
  margin-bottom: 24px;
  padding: 24px;
  min-height: 180px;
}

.profile-info {
  position: relative;
  display: flex;
  align-items: flex-start;
  gap: 24px;
}

.avatar {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  object-fit: cover;
}

.user-meta {
  flex: 1;
}

.username {
  font-size: 24px;
  margin: 0 0 8px;
  color: var(--text-color);
}

.bio {
  color: var(--text-light);
  margin: 0 0 16px;
  line-height: 1.5;
}

.stats {
  display: flex;
  gap: 24px;
  margin-bottom: 16px;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
}

.value {
  font-size: 18px;
  font-weight: 500;
  color: var(--text-color);
}

.label {
  font-size: 14px;
  color: var(--text-light);
}

.follow-btn {
  padding: 8px 24px;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
}

.follow-btn {
  background: var(--primary-color);
  border: none;
  color: white;
}

.follow-btn.following {
  background: var(--border-color);
}

.avatar-container {
  position: relative;
  cursor: pointer;
  width: 120px;
  height: 120px;
}

.avatar-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s;
  pointer-events: none;
}

.avatar-container:hover .avatar-overlay {
  opacity: 1;
}

.avatar-overlay i {
  color: white;
  font-size: 24px;
}

.cropper-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.cropper-container {
  background: white;
  border-radius: 8px;
  width: 90%;
  max-width: 600px;
  max-height: 90vh;
  display: flex;
  flex-direction: column;
}

.cropper-header {
  padding: 16px;
  border-bottom: 1px solid var(--border-color);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.cropper-header h3 {
  margin: 0;
  font-size: 18px;
}

.close-btn {
  background: none;
  border: none;
  font-size: 20px;
  cursor: pointer;
  color: var(--text-light);
}

.cropper-content {
  flex: 1;
  min-height: 400px;
  padding: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
  background: #f5f5f5;
}

.cropper-content :deep(.vue-advanced-cropper) {
  height: 100%;
  width: 100%;
}

.upload-placeholder {
  text-align: center;
}

.select-btn {
  padding: 12px 24px;
  background: var(--primary-color);
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 8px;
}

.cropper-footer {
  padding: 16px;
  border-top: 1px solid var(--border-color);
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.cancel-btn,
.confirm-btn {
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
}

.cancel-btn {
  background: none;
  border: 1px solid var(--border-color);
}

.confirm-btn {
  background: var(--primary-color);
  color: white;
  border: none;
}

.confirm-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
}
</style> 